<?php

namespace Endor\EndorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Endor\EndorBundle\Entity\Ventas;
use Endor\EndorBundle\Form\VentasType;

use Symfony\Component\HttpFoundation\Response;

include_once('bundles/EndorBundle/Plugins/MPDF54/mpdf.php');

/**
 * Ventas controller.
 *
 */
class VentasController extends Controller {

    private function DeepLoad($entity) {
        $em = $this->getDoctrine()->getEntityManager();
        $items = $em->getRepository('EndorBundle:ItemsVentas')->findBy(array('Venta' => $entity->getId()));
        $entity->setItemsVentas($items);

        return $entity;
    }

    /**
     * Lists all Ventas entities.
     *
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('EndorBundle:Ventas')->findAll();

        return $this->render('EndorBundle:Ventas:index.html.twig', array(
                    'entities' => $entities
                ));
    }

    /**
     * Finds and displays a Ventas entity.
     *
     */
    public function showAction($id, $_format) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('EndorBundle:Ventas')->find($id);
        $entity = $this->DeepLoad($entity);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Ventas entity.');
        }

        if($_format == 'pdf'){
            $response = new Response();
            $response->headers->set('Content-Type', 'text/pdf');
            $response->send();
            
            $mpdf = new \mPDF('c','A4','','',32,25,97,25,16,13); 
            
            $mpdf->SetDisplayMode('fullpage');
            $mpdf->list_indent_first_level = 0;            
            
            $stylesheet = file_get_contents('bundles/EndorBundle/css/reports.css');
            $mpdf->WriteHTML($stylesheet,1);
            $mpdf->SetHTMLHeader($this->renderView('EndorBundle:ReportsFormat:salidas.header.html.twig',array('entity' => $entity)));            
            $mpdf->AddPage('L');
            $mpdf->WriteHTML($this->renderView('EndorBundle:ReportsFormat:salidas.html.twig',array('entity' => $entity)),2);
            $mpdf->setFooter('{PAGENO} de 1 paginas||{PAGENO} de 1 paginas');
            $content = $mpdf->Output();
            
            return $response;
        }else{
             $deleteForm = $this->createDeleteForm($id);
             return $this->render('EndorBundle:Ventas:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),
                ));
        }
        
       
      
    }

    /**
     * Displays a form to create a new Ventas entity.
     *
     */
    public function newAction() {
        $entity = new Ventas();
        $form = $this->createForm(new VentasType(), $entity);

        $em = $this->getDoctrine()->getEntityManager();
        $articulos = $em->getRepository("EndorBundle:Articulos")->findAll();

        return $this->render('EndorBundle:Ventas:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    "articulos" => $articulos,
                ));
    }

    /**
     * Creates a new Ventas entity.
     *
     */
    public function createAction() {
        $entity = new Ventas();
        $request = $this->getRequest();
        $form = $this->createForm(new VentasType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity->setFechaCreacion(date_create());
            $fechaRadicacion = $request->get("fechaRadicacion");
            $entity->setFecha(date_create($fechaRadicacion));
            $estado = $em->getRepository('EndorBundle:EstadosVentas')->find(5);
            $entity->setEstadoVenta($estado);

            $em->persist($entity);

            $array = $request->get("ItemsCompras", array());
            foreach ($array as $value) {
                $articulo = $em->find("EndorBundle:Articulos", $value["idArticulo"]);

                $item = new \Endor\EndorBundle\Entity\ItemsVentas();
                $item->setArticulo($articulo);
                $item->setVenta($entity);
                $item->setArticulo($articulo);
                $item->setValor($value["valor"]);
                $item->setCantidad($value["cantidad"]);
                $item->setIsTipoUnidad($value["unidad"]);

                $em->persist($item);
            }

            $em->flush();
            
            return $this->redirect($this->generateUrl('ventas_show', array('id' => $entity->getId())));
        }

        return $this->newAction();
    }

    /**
     * Displays a form to edit an existing Ventas entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('EndorBundle:Ventas')->find($id);
        $entity = $this->DeepLoad($entity);

        $em = $this->getDoctrine()->getEntityManager();
        $articulos = $em->getRepository("EndorBundle:Articulos")->findAll();

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Ventas entity.');
        }

        $editForm = $this->createForm(new VentasType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('EndorBundle:Ventas:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                    "articulos" => $articulos,
                ));
    }

    public function cambiarEstadoAction($idVenta, $idEstado) {
        $em = $this->getDoctrine()->getEntityManager();

        /* @var $entity Compras */
        $entity = $em->getRepository('EndorBundle:Ventas')->find($idVenta);

        if ($entity->getEstadoVenta()->getId() == 5) {
            $entity->setEstadoVenta($em->getRepository('EndorBundle:EstadosVentas')->find($idEstado));
            $em->persist($entity);
            $em->flush();
        }
        return $this->redirect($this->generateUrl('ventas'));
    }

    public function entregarAction($idVenta) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('EndorBundle:Ventas')->find($idVenta);
        $entity = $this->DeepLoad($entity);

        if ($entity->getEstadoVenta()->getId() == 1) {
            $itemsventas = $em->getRepository('EndorBundle:ItemsVentas')->findBy(array(
                "Venta" => $idVenta
                    ));
            $bodegas = $em->getRepository('EndorBundle:Bodegas')->findBy(array(
                "habilitado" => 1
                    ));
            return $this->render('EndorBundle:Ventas:entregar.html.twig', array(
                        'entity' => $entity,
                        'bodegas' => $bodegas
                    ));
        }

        return $this->redirect($this->generateUrl('ventas'));
    }

    public function confirmarEntregaAction() {
        $em = $this->getDoctrine()->getEntityManager();

        $request = $this->getRequest();

        $idVenta = $request->get("idVenta");
        /* @var $venta Ventas */
        $venta = $em->getRepository('EndorBundle:Ventas')->find($idVenta);
        $venta->setEstadoVenta($em->getRepository('EndorBundle:EstadosVentas')->find(2));
        $em->persist($venta);

        $items = $request->get("items");

        foreach ($items as $item) {
            if (array_key_exists("check", $item)) {
                $salida = new \Endor\EndorBundle\Entity\Salidas();

                /* @var $itemVenta ItemsVentas */
                $itemVenta = $em->getRepository('EndorBundle:ItemsVentas')->find($item["idItemVenta"]);
                $bodega = $em->getRepository('EndorBundle:Bodegas')->find($item["bodega"]);
                $articulo = $em->getRepository('EndorBundle:Articulos')->find($item["articulo"]);

                $salida->setArticulo($articulo);
                $salida->setCliente($venta->getCliente());
                $salida->setItemVenta($itemVenta);
                $salida->setBodega($bodega);
                $salida->setCantidad($item["cantidad"]);
                $salida->setFecha(date_create($item["fecha"]));

                $em->persist($salida);
            }
        }

        $em->flush();
        return $this->redirect($this->generateUrl("ventas"));
    }

    /**
     * Edits an existing Ventas entity.
     *
     */
    public function updateAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('EndorBundle:Ventas')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Ventas entity.');
        }

        $editForm = $this->createForm(new VentasType(), $entity);
        $deleteForm = $this->createDeleteForm($id);
        
        $request = $this->getRequest();
        $fechaRadicacion = $request->get("fechaRadicacion");
        $entity->setFecha(date_create($fechaRadicacion));

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $itemsChanges = $request->get("ItemsCompras");

            if (!is_null($itemsChanges) && count($itemsChanges) > 0) {
                foreach ($itemsChanges as $value) {
                    if ($value["status"] == "New" || $value["status"] == "Modified") {

                        if ($value["status"] == "New") {
                            $item = new \Endor\EndorBundle\Entity\ItemsVentas();
                            $articulo = $em->find("EndorBundle:Articulos", $value["idArticulo"]);

                            $item->setVenta($entity);
                            $item->setArticulo($articulo);
                        } else {
                            $item = $em->find("EndorBundle:ItemsVentas", $value["id"]);
                        }

                        $item->setValor($value["valor"]);
                        $item->setCantidad($value["cantidad"]);
                        $item->setIsTipoUnidad($value["unidad"]);

                        $em->persist($item);
                    } else if ($value["status"] == "Removed") {
                        $item = $em->find("EndorBundle:ItemsVentas", $value["id"]);
                        $em->remove($item);
                    }
                }
            }

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('ventas_show', array('id' => $entity->getId())));
        }

        return $this->editAction($id);
    }

    /**
     * Deletes a Ventas entity.
     *
     */
    public function deleteAction($id) {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('EndorBundle:Ventas')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Ventas entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('ventas'));
    }

    private function createDeleteForm($id) {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

}
